import { ref } from 'vue'
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
const UnSeverdate = fn => {
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }]) => {
      console.log(isIntersecting, stop)
      if (isIntersecting) {
        stop()

        fn()
      }
    },
    { threshold: 0 }
  )
  return target
}
// 封装一个通用的倒计时的函数 useCountDown
// 用法： const { time, start, stop } = useCountDown()
//   time : 是一个响应式数据。每隔1秒，值减一(5->4->3...)。如果在视图上使它，视图会自动更新。
//   start: 用来启动倒计时,传入初始值。如：start(20)， time的值从20 -> 19 -> 18 ....
//   stop: 停止倒计时
const useCountDown = () => {
  const time = ref(0)
  // pause: 停止
  // resume: 开始
  const { pause, resume } = useIntervalFn(() => {
    time.value--
    if (time.value <= 0) {
      pause()
    }
  }, 1000, { immediate: false })

  const start = (num) => {
    // 赋初值
    time.value = num
    // 开始倒计时
    resume()
  }

  const stop = () => {
    pause()
  }
  return { time, start, stop }
}

export {
  UnSeverdate,
  useCountDown
}
